package com.servlet;

import com.service.UserService;
import com.util.Md5Util;
import com.util.SpringUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;

@WebServlet("/register2")
public class Register2 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、复杂请求的接收
//        获取数据
//        （1）创建FileItem工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
//        (2)创建一个上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
//        (3)解决上传文件名的中文乱码
        upload.setHeaderEncoding("UTF-8");
//        (4)判断是否是上传请求（复杂请求）
        if (!ServletFileUpload.isMultipartContent(req)) {
            //按照传统方式获取数据
            return;
        }

//        （5）解析请求，获取文件数据
        List<FileItem> list = null;
        try {
            list = upload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

//        （6）遍历数据项集合
        String username=null;
        String password1=null;
        String password2=null;
        String yzm=null;
        String touxiang=null;
        for (FileItem item : list) {
//            是否是表单的普通字段
            if (item.isFormField()) {
                //普通字段
                String fieldName = item.getFieldName();
                String fieldValue = item.getString("utf-8");
//                System.out.println(fieldName + "=" + fieldValue);
                if (fieldName.equals("username")){
                    username=fieldValue;
                }
                if (fieldName.equals("password1")){
                    password1=fieldValue;
                }
                if (fieldName.equals("password2")){
                    password2=fieldValue;
                }
                if (fieldName.equals("yzm")){
                    yzm=fieldValue;
                }


            } else {
                //文件上传字段
//                原始文件名：
                String fileName = item.getName();
                fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);

//               获取文件的数据
                InputStream in = item.getInputStream();
//              保存位置
//                生成一个唯一的文件名：
                String newFileName = "";
                String extFileName = fileName.substring(fileName.lastIndexOf("."));
                newFileName = UUID.randomUUID().toString() + extFileName;

                touxiang=newFileName;

                String save = "D:\\upload\\" + newFileName;
                FileOutputStream out = new FileOutputStream(save);

//                读写操作
                byte[] bytes = new byte[1024];
                int i = in.read(bytes);
                while (i != -1) {
                    out.write(bytes, 0, i);
                    i = in.read(bytes);
                }
                out.close();
                in.close();
//              文件存储到服务器上完毕。
            }
        }

        PrintWriter writer = resp.getWriter();
        String verifyCode =(String) req.getSession().getAttribute("verifyCode");
        if (!yzm.equalsIgnoreCase(verifyCode)){
            writer.write("-1");
            return;
        }


        String md5Password1=null;
        String md5Password2=null;
        try {
            md5Password1 = Md5Util.toMd5(password1);
            md5Password2=Md5Util.toMd5(password2);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }


        UserService userService = SpringUtil.getBean(UserService.class);
        int i = userService.register(username, md5Password1, md5Password2,touxiang);


        writer.write(i+"");
        writer.close();



    }
}